<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-button
        type="primary"
        plain
        icon="el-icon-plus"
        size="mini"
        @click="handleAdd"
        v-hasPermi="['system:sales:add']"
      >创建订单</el-button>
      <el-button
        type="success"
        plain
        icon="el-icon-edit"
        size="mini"
        :disabled="single"
        @click="handleUpdate"
        v-hasPermi="['system:sales:edit']"
      >批量出库</el-button>&nbsp;&nbsp;&nbsp;
      <el-input
        v-model="queryParams.updater"
        placeholder="请输入订单编号"
        clearable
        @keyup.enter.native="handleQuery"
        style="width: 250px ;"
      />
      <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
    </el-form>

    <el-table v-loading="loading" :data="salesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单编号" align="center" prop="sn" width="180px"/>
      <el-table-column label="下单用户" align="center" prop="ownerName" />
      <el-table-column label="下单时间" align="center" prop="orderTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="仓库名称" align="center" prop="warehouseName" />
      <el-table-column label="所属部门" align="center" prop="deptName" />
      <el-table-column label="配送方式" align="center" prop="deliveryType" />
      <el-table-column label="实付金额" align="center" prop="payPrice" />
      <el-table-column label="订单状态" align="center" prop="status" />
      <el-table-column label="支付状态" align="center" prop="paymentStatus" />
      <el-table-column label="销售渠道" align="center" prop="source" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status === '待审核'"
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleAudit(scope.row)"
            v-hasPermi="['xiaoshou:sale:audit']"
          >审核</el-button>

          <!-- 出库按钮 -->
          <el-button
            v-if="scope.row.status === '待出库'"
            size="mini"
            type="text"
            icon="el-icon-truck"
            @click="handleOutbound(scope.row)"
            v-hasPermi="['system:sales:outbound']"
          >出库</el-button>

          <!-- 设为已支付按钮 -->
          <el-button
            v-if="scope.row.status === '待出库'"
            size="mini"
            type="text"
            icon="el-icon-money"
            @click="handlePay(scope.row)"
            v-hasPermi="['system:sales:pay']"
          >设为已支付</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 审核订单对话框 - 独立于添加/编辑对话框 -->
    <el-dialog
      :title="'审核订单 - ' + auditForm.sn"
      :visible.sync="auditDialogVisible"
      width="800px"
      append-to-body>
      <el-form ref="auditFormRef" :model="auditForm" label-width="100px">
        <!-- 订单基本信息 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="订单编号:">
              <el-input v-model="auditForm.sn" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称:">
              <el-input v-model="auditForm.ownerName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仓库名称:">
              <el-input v-model="auditForm.warehouseName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属部门:">
              <el-input v-model="auditForm.deptName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销售金额:">
              <el-input v-model="auditForm.totalPrice" disabled>
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="应付金额:">
              <el-input v-model="auditForm.payPrice" disabled>
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 商品明细表格 -->
        <el-divider>商品明细</el-divider>
        <el-table :data="auditForm.goodsList" border>
          <el-table-column prop="sn" label="商品编号" width="120"></el-table-column>
          <el-table-column prop="name" label="商品名称" width="150"></el-table-column>
          <el-table-column prop="specName" label="规格"></el-table-column>
          <el-table-column prop="num" label="数量" width="80" align="center"></el-table-column>
          <el-table-column prop="price" label="单价" width="100" align="right">
            <template slot-scope="scope">
              {{ scope.row.price | currency }}
            </template>
          </el-table-column>
          <el-table-column label="金额" width="120" align="right">
            <template slot-scope="scope">
              {{ (scope.row.price * scope.row.num) | currency }}
            </template>
          </el-table-column>
        </el-table>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="danger" @click="rejectAudit">审核拒绝</el-button>
        <el-button type="primary" @click="approveAudit">审核通过</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改销售订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="下单时间" prop="orderTime">
          <el-date-picker clearable
                          v-model="form.orderTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择下单时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="仓库名称" prop="warehouseId">
          <el-select
            v-model="form.warehouseId"
            placeholder="请选择仓库名称"
            clearable
          >
            <el-option
              v-for="warehouse in warehouseOptions"
              :key="warehouse.id"
              :label="warehouse.name"
              :value="warehouse.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="下单用户" prop="ownerName">
          <el-input v-model="form.ownerName" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="所属部门">
          <el-cascader
            v-model="form.deptId"
            :options="deptTree"
            :props="{ checkStrictly: true, value: 'id', label: 'name' }"
            placeholder="请选择所属部门"
            @change="handleDeptChange">
          </el-cascader>
        </el-form-item>
        <el-form-item label="配送方式" prop="deliveryType">
          <el-select v-model="form.deliveryType" placeholder="配送方式">
            <el-option label="快递" value="快递" />
            <el-option label="自提" value="自提" />
          </el-select>
        </el-form-item>
        <el-form-item label="实付金额" prop="payPrice">
          <el-input v-model="form.payPrice" placeholder="请输入付款金额" v-bind:disabled="disabled"/>
        </el-form-item>
        <el-form-item label="销售渠道" prop="source">
          <el-select v-model="form.source" placeholder="请输入销售渠道">
            <el-option label="平台" value="平台" />
            <el-option label="线下销售" value="线下销售" />
          </el-select>
        </el-form-item>

<!--        商品明细-->
        <el-table :data="goodsList" border style="width: 100%; margin-bottom: 20px;">
          <el-table-column prop="sn" label="商品编号" width="120"></el-table-column>
          <el-table-column prop="name" label="商品名称" width="150"></el-table-column>
<!--          <el-table-column prop="specName" label="规格型号" width="120"></el-table-column>-->
          <el-table-column prop="countNum" label="剩余库存" width="100"></el-table-column>
          <el-table-column label="数量" width="100">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.num"
                :min="1"
                size="mini"
                @change="calculateRow(scope.row)">
              </el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="单价" width="120">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.price"
                @blur="calculateRow(scope.row)">
              </el-input>
            </template>
          </el-table-column>
          <el-table-column label="金额" width="120">
            <template slot-scope="scope">
              {{ scope.row.amount || '0.00' }}
            </template>
          </el-table-column>
          <el-table-column label="优惠金额" width="120">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.discountPrice"
                @blur="calculateRow(scope.row)">
              </el-input>
            </template>
          </el-table-column>
          <el-table-column label="合计" width="120">
            <template slot-scope="scope">
              {{ scope.row.total }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="danger"
                @click="removeGoods(scope.$index)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-button @click="openGoodsDialog">添加商品</el-button>

          <el-dialog title="选择商品" :visible.sync="showGoodsDialog" width="80%">
          <!-- 这里放商品选择表格，可以从后端获取商品数据 -->
          <el-table :data="allGoodsList" @selection-change="handleGoodsSelection">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="id" label="入库单号"></el-table-column>
            <el-table-column prop="sn" label="商品编号"></el-table-column>
            <el-table-column prop="name" label="商品名称"></el-table-column>
<!--            <el-table-column prop="specName" label="规格型号"></el-table-column>-->
            <el-table-column prop="countNum" label="当前库存" width="100">
              <template slot-scope="scope">
                {{ scope.row.countNum || 0 }}
              </template>
            </el-table-column>
          </el-table>

          <div slot="footer" class="dialog-footer">
            <el-button @click="showGoodsDialog = false">取消</el-button>
            <el-button type="primary" @click="confirmAddGoods">确定</el-button>
          </div>
        </el-dialog>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
import { listSales, getSales, delSales, addSales, updateSales ,getOrderGoods} from "@/api/system/sale";
import { getWarehouseDeptList } from "@/api/system/sale";

import { listWarehouse } from "@/api/system/warehouse";

import {auditSales,outboundSales,paySales} from "@/api/system/sale"
import {getDeptTree} from "@/api/procurementmanagement/plan";
import {listGoods} from "../../../api/system/sale";
import request from '@/utils/request';

export default {
  filters: {
    currency(value) {
      if (typeof value !== 'number') {
        return '0.00';
      }
      return value.toFixed(2); // 保留 2 位小数
    }
  },
  name: "Sales",
    data() {
    return {
      allGoodsList: [],
      isAuditMode: false,  // 是否处于审核模式
      auditForm: {},       // 存储待审核订单数据
      auditDialogVisible: false,
      showGoodsDialog: false,
      // 仓库选项
      warehouseOptions: [],// 用于存储仓库和部门的数据
      selectedGoods: [],
      goodsList:[],
      disabled:false,
      deptTree: [],
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      salesList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: null,
        sn: null,
        status: null,
        payment_status: null,
        payment_time: null,
        owner_id: null,
        owner_name: null,
        owner_mobile: null,
        order_time: null,
        warehouse_id: null,
        warehouse_name: null,
        dept_id: null,
        dept_name: null,
        marketing_id: null,
        marketing_name: null,
        total_price: null,
        discount_price: null,
        tax_price: null,
        pay_price: null,
        deposit_price: null,
        attachment: null,
        remark: null,
        type: null,
        source: null,
        source_id: null,
        delivery_type: null,
        ship_region_ids: null,
        ship_region_names: null,
        ship_address: null,
        store_id: null,
        store_name: null,
        warehouse_out_flag: null,
        warehouse_out_id: null,
        ship_flag: null,
        ship_time: null,
        logistics_company_id: null,
        logistics_company_name: null,
        logistics_tracking_number: null,
        deleted: null,
        create_time: null,
        update_time: null,
        creator: null,
        updater: null
      },
      form: {
        totalPrice: 0, // 总金额
        discountPrice: 0, // 优惠金额
        taxPrice: 0, // 税额
        payPrice: 0 // 应付金额
      },

      rules: {}
    };
  },
  watch: {
    // 监听仓库选择
    'form.warehouseId': function(newVal) {
      if (newVal && this.form.deptId) {
        this.loadGoodsStock(newVal, this.form.deptId);
      }
    },
    // 监听部门选择
    'form.deptId': function(newVal) {
      if (newVal && this.form.warehouseId) {
        this.loadGoodsStock(this.form.warehouseId, newVal);
      }
    }
  },
  created() {
    this.getList();
    this.getWarehouseOptions(); // 获取仓库和部门数据
    // this.handleOutbound();
    // this.handlePay();
  },
  methods: {
    refreshList() {
      this.getList();
    },

    // 监听刷新事件
    created() {
      this.$on('refresh-out', this.refreshList);
    },

    // 销毁时移除监听
    beforeDestroy() {
      this.$off('refresh-out');
    },

    calculateRow(row) {
      const price = parseFloat(row.price) || 0;
      const num = parseInt(row.num) || 0;
      const discountPrice = parseFloat(row.discountPrice) || 0;
      const taxRate = parseFloat(row.taxRate) || 0;

      // 检查库存是否足够
      if (num > row.countNum) {
        this.$message.error(`商品 ${row.name} 库存不足，最大可用数量为 ${row.countNum}`);
        row.num = row.countNum; // 自动调整为最大可用数量
        return;
      }

      // 计算金额
      row.amount = (price * num).toFixed(2);
      row.taxAmount = (price * num * taxRate / 100).toFixed(2);
      row.total = (price * num - discountPrice).toFixed(2);

      // 计算订单总金额
      this.calculateOrderTotal();
    },

    // 计算订单总金额
    calculateOrderTotal() {
      let totalPrice = 0;
      let totalDiscount = 0;
      let totalTax = 0;
      let payPrice = 0;

      this.goodsList.forEach(item => {
        totalPrice += parseFloat(item.amount) || 0;
        totalDiscount += parseFloat(item.discountPrice) || 0;
        totalTax += parseFloat(item.taxAmount) || 0;
      });

      payPrice = totalPrice - totalDiscount + totalTax;

      // 更新表单中的金额字段
      this.form.totalPrice = totalPrice.toFixed(2);
      this.form.discountPrice = totalDiscount.toFixed(2);
      this.form.taxPrice = totalTax.toFixed(2);
      this.form.payPrice = payPrice.toFixed(2);
    },
    openGoodsDialog() {
      console.log("打开商品对话框");
      this.showGoodsDialog = true;
      listGoods().then(response => {
        console.log("商品数据响应:", response);
        // 处理不同的响应格式
        this.allGoodsList = response.rows || response.data || [];
      }).catch(error => {
        console.error("获取商品列表错误:", error);
        this.$message.error("获取商品列表失败");
      });
    },
    loadGoodsData() {
      this.showGoodsDialog = true;
      listGoods({
        warehouseId: this.form.warehouseId // 从表单中获取当前选择的仓库ID
      }).then(response => {
        this.allGoodsList = response.data || response.rows || [];
      });
    },
    // testGoodsApi() {
    //   listGoods().then(res => {
    //     console.log("API响应:", res);
    //     this.$notify.success({
    //       title: '成功',
    //       message: `获取到${res.data.length}条商品数据`
    //     });
    //   }).catch(err => {
    //     this.$notify.error({
    //       title: '错误',
    //       message: '获取商品数据失败'
    //     });
    //   });
    // },
    confirmAddGoods() {
      // 检查所有选中的商品库存是否足够
      const insufficientStockItems = this.selectedGoods.filter(good => {
        const requiredQuantity = 1; // 默认添加1个，或者可以根据需要修改
        return good.countNum < requiredQuantity;
      });

      if (insufficientStockItems.length > 0) {
        const itemNames = insufficientStockItems.map(item => item.name).join(', ');
        this.$message.error(`以下商品库存不足: ${itemNames}`);
        return;
      }

      // 库存足够，添加商品
      this.selectedGoods.forEach(good => {
        const existingIndex = this.goodsList.findIndex(item => item.id === good.id);
        const requiredQuantity = 1; // 默认添加1个

        if (existingIndex >= 0) {
          // 检查增加数量后是否超过库存
          if (this.goodsList[existingIndex].num + requiredQuantity > good.countNum) {
            this.$message.error(`商品 ${good.name} 库存不足，无法添加更多`);
            return;
          }
          this.goodsList[existingIndex].num += requiredQuantity;
          this.calculateRow(this.goodsList[existingIndex]);
        } else {
          this.goodsList.push({
            ...good,
            id: good.id,
            sn: good.sn,
            name: good.name,
            specName: good.specName,
            price: good.price,
            num: requiredQuantity,
            discountPrice: 0,
            taxRate: 0,
            amount: (good.price * requiredQuantity).toFixed(2),
            taxAmount: 0,
            total: (good.price * requiredQuantity).toFixed(2),
            remark: '',
            countNum: good.countNum // 保留库存数量用于后续检查
          });
        }
      });

      this.showGoodsDialog = false;
      this.selectedGoods = [];
      this.calculateOrderTotal();
    },
    // 计算单行金额
    calculateAmount(row) {
      // 确保price和num是数字类型
      const price = parseFloat(row.price) || 0;
      const num = parseInt(row.num) || 0;
      const discountPrice = parseFloat(row.discountPrice) || 0;

      // 计算金额并保留2位小数
      row.amount = (price * num).toFixed(2);
      row.total = (price * num - discountPrice).toFixed(2);

      // 如果需要，可以触发总金额重新计算
      this.calculateTotal();
    },

    calculateTotal() {
      // 计算所有商品的总金额
      this.form.totalAmount = this.goodsList.reduce((sum, item) => {
        return sum + (parseFloat(item.amount) || 0);
      }, 0).toFixed(2);
      let totalAmount = 0;
      let totalDiscount = 0;
      let grandTotal = 0;

      this.goodsList.forEach(item => {
        totalAmount += parseFloat(item.amount) || 0;
        totalDiscount += parseFloat(item.discount) || 0;
        grandTotal += parseFloat(item.total) || 0;
      });

      this.form.totalAmount = totalAmount.toFixed(2);
      this.form.totalDiscount = totalDiscount.toFixed(2);
      this.form.grandTotal = grandTotal.toFixed(2);

    },

    // 删除商品
    removeGoods(index) {
      this.goodsList.splice(index, 1);
    },

    // 处理商品选择
    handleGoodsSelection(selection) {
      this.selectedGoods = selection;
    },
    getList() {
      this.loading = true;
      listSales(this.queryParams).then(response => {
        this.salesList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(error => {
        this.loading = false;
        console.error("获取订单列表失败:", error);
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        id: null,
        sn: null,
        ownerName: null,
        orderTime: null,
        warehouseName: null,
        deptName: null,
        deliveryType: null,
        payPrice: null,
        status: null,
        paymentStatus: null,
        source: null,
        paymentTime: null,
        shipAddress: null,
      };
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.getWarehouseOptions();
      this.getDeptTree();
      this.getList();
      this.title = "添加销售订单";
      this.disabled = true;
      this.form = {
        ...this.form,
        paymentStatus: "未支付",
        status: "待审核"
      };
    },
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSales(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.getWarehouseOptions();
        this.getDeptOptions();
        this.title = "修改销售订单";
      });
    },
    approveAudit() {
      this.$confirm('确定要通过此订单审核吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        auditSales(this.auditForm.id, { action: 'approve' }).then(response => {
          this.$message.success('审核通过成功');
          this.auditDialogVisible = false;
          this.getList(); // 刷新订单列表
          this.$emit('refresh-out'); // 通知出库管理刷新
        });
      });
    },

    rejectAudit() {
      this.$confirm('确定要拒绝此订单吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        auditSales(this.auditForm.id, { action: 'reject' }).then(response => {
          this.$message.success('订单已拒绝');
          this.auditDialogVisible = false;
          this.getList();
        });
      });
    },
    /** 获取仓库列表 */
    getWarehouseOptions() {
      listWarehouse().then(response => {
        response.rows.forEach(warehouse => {
          warehouse.warehouseName = warehouse.name;
        });
        this.warehouseOptions = response.rows;
      });
    },

    handleAudit(row) {
      this.auditForm = {
        ...row,
        goodsList: [] // 初始化为空数组
      };

      // 获取商品明细
      getOrderGoods(row.id).then(response => {
        console.log('商品明细响应:', response); // 调试输出

        // 处理不同响应格式
        const goodsData = response.data || response.rows || [];

        // 确保数据格式正确
        this.auditForm.goodsList = goodsData.map(item => ({
          id: item.id,
          sn: item.sn || '无编号',
          name: item.name || '未知商品',
          specName: item.specName || item.specification || '/',
          num: item.countNum || 1,
          price: item.price || item.productPrice || 0,
          productPrice: item.productPrice || item.price || 0,
          amount: (item.price || 0) * (item.num || 1)
        }));

        this.auditDialogVisible = true;
      }).catch(error => {
        console.error('获取商品明细失败:', error);
        this.$message.error('获取商品明细失败');
        this.auditForm.goodsList = []; // 设置为空数组避免报错
        this.auditDialogVisible = true;
      });
    },

    // 出库订单
    handleOutbound(row) {
      if (!row || !row.id) {
        console.error('Invalid row data:', row);
        return;
      }
      this.$modal.confirm('是否确认出库订单编号为"' + row.sn + '"的数据项？').then(() => {
        return outboundSales(row.id);
      }).then(() => {
        this.getList(); // 刷新订单列表
        this.$emit('refresh-out'); // 通知出库管理刷新
        this.$modal.msgSuccess("出库成功");
      }).catch(() => {});
    },
    // 设为已支付
    handlePay(row) {
      if (!row || !row.id) {
        console.error('Invalid row data:', row);
        return;
      }

      this.$modal.confirm('是否确认将订单编号为"' + row.sn + '"的数据项设为已支付？').then(() => {
        return paySales(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("设为已支付成功");
      }).catch(() => {});
    },
    handleDeptChange(value) {
      if (value.length > 0) {
        // 获取选中的最后一级部门的 ID
        const deptId = value[value.length - 1];
        // 根据 ID 查找对应的部门对象
        const selectedDept = this.findDeptById(this.deptTree, deptId);
        if (selectedDept) {
          this.form.deptId = selectedDept.id; // 保存子部门的 ID
          this.form.deptName = selectedDept.name; // 保存子部门的名称
          console.log(this.form.deptName,this.form.deptId);
        }
      } else {
        this.form.deptId = null;
        this.form.deptName = null;
      }
    },
    findDeptById(tree, id) {
      for (let dept of tree) {
        if (dept.id === id) {
          return dept; // 如果找到匹配的 ID，返回该部门对象
        }
        if (dept.children && dept.children.length > 0) {
          const result = this.findDeptById(dept.children, id); // 递归查找子部门
          if (result) return result;  // 如果在子部门中找到，返回结果
        }
      }
      return null; // 如果未找到，返回 null
    },
    getDeptTree() {
      getDeptTree().then(response => {
        console.log(response.data)
        this.deptTree = response.data;
      });
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 获取选中的仓库对象
          const selectedWarehouse = this.warehouseOptions.find(
            warehouse => warehouse.id === this.form.warehouseId
          );

          const formData = {
            ...this.form,
            warehouseId: this.form.warehouseId,
            warehouseName: selectedWarehouse ? selectedWarehouse.name : null, // 确保 warehouseName 不为空
            goodsList: this.goodsList.map(item => ({
              id: item.id,
              num: item.num,
              price: item.price
            }))
          };

          if (this.form.id != null) {
            updateSales(formData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSales(formData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除销售订单编号为"' + ids + '"的数据项？').then(function () {
        return delSales(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    handleExport() {
      this.download('system/sales/export', {
        ...this.queryParams
      }, `sales_${new Date().getTime()}.xlsx`)
    }
  }

};
</script>


